package com.loan.task;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.loan.enums.S;
import com.loan.model.Loan;
import com.loan.model.Repay;
import com.loan.util.DateUtil;

/**
 * 逾期定时任务
 * @author 无处不在的二叔
 */
public class RepayExpireTask implements Runnable{
    
	@Override 
	@Before(Tx.class)
	public void run() {
		Date now = new Date();
		Set<Integer> set = new HashSet<Integer>();
		Repay.dao.find("select * from repay where repay_time<? and status<>'已结清'", DateUtil.format(now)).forEach(n->{
			int day = DateUtil.diff(n.getRepayTime(),now);
			if(day>3) {
				if(n.getApplyPeriod()==n.getPeriod()) {
					n.setStatus(S.REPAY_DELAY).setAmount(800).setInterest(550.0).setPledge(0).setPeriodTotal(1350.0).update();
					Loan ln = Loan.dao.findById(n.getLoanId());
					ln.setStatus(S.REPAY_DELAY).update();
				}else {
					n.setInterest(500.0).setAmount(0).setPledge(0).setPeriodTotal(500.0).update();
				}
			}else {
				n.setInterest(Double.valueOf((7+day)*50)).setStatus(S.REPAY_DELAY).setPeriodTotal(n.getAmount()+n.getInterest()).update();
				Loan ln = Loan.dao.findById(n.getLoanId());
				ln.setStatus(S.REPAY_DELAY).update();
			}
			set.add(n.getLoanId());
		});
		for(int loanId : set) {
			Double total = Db.queryDouble("select sum(period_total) as total from repay where loan_id=? ",loanId);
			Db.update("update repay set total=? where loan_id=?",total,loanId);
		}
	}
}
